from django.conf import settings
from django.conf.global_settings import MEDIA_ROOT
from django.shortcuts import render, redirect
from django.http import HttpResponse
from task_con.models import Task, DataUpload, Taskdata
from django.conf import settings

from django.core.files.uploadedfile import InMemoryUploadedFile
import zipfile
import os
import time
import random
import string

from user_mng.models import users

data_file_num = []


def task_con(request):
    user_list = {i.user_account: [i.user_name, i.user_type] for i in users.objects.all()}
    if not request.session.get('account'):
        staue = 'login'
        name = '请登录'
        typee = '1209'
    else:
        staue = 'logout'
        name = user_list[request.session.get('account')][0]  # name
        typee = user_list[request.session.get('account')][1]  # user_type
    return render(request, 'task_con/task_con.html', {'name': name, 'staues': staue, 'type': typee})


def check_data(request):
    user_list = {i.user_account: [i.user_name, i.user_type] for i in users.objects.all()}
    if not request.session.get('account'):
        staue = 'login'
        name = '请登录'
        typee = '1209'
    else:
        staue = 'logout'
        name = user_list[request.session.get('account')][0]  # name
        typee = user_list[request.session.get('account')][1]  # user_type
    global data_file_num
    # publisher_id = request.session.get('user_id')#TODO
    user_list = {i.user_account: [i.user_id] for i in users.objects.all()}
    publisher_id = user_list[request.session.get('account')][0]
    work_list = DataUpload.objects.filter(publisher_id=publisher_id)
    # i_d = []
    # group_id_list = []
    group_id_num = {}
    group_upload_time = {}
    data=[]
    for row in work_list:
        group_id_num[row.data_group] = group_id_num.get(row.data_group, 0) + 1
        group_upload_time[row.data_group] = row.data_upload_time

        # if row.data_group not in i_d:
        #     i_d.append(row.data_group)
    # group_id_set = set(group_id_list)
    # for i in group_id_set:
    #     group_id_to_num[i] = group_id_list.count(i)
    print(group_id_num)
    for i in group_id_num:
        data.append({'num':group_id_num[i],'time':group_upload_time[i],'group_id':i})
    print(data)
    if request.method == "GET":
        return render(request, 'task_con/check_data_2.html', {'datas': data, 'name': name, 'staues': staue, 'type': typee})
        # return render(request, 'task_con/check_data_2.html', {'filenum': i_d, 'group_id_num': group_id_num,
        #                                                       'group_upload_time': group_upload_time})

    data_file_num = request.POST.getlist("data")
    print(data_file_num)
    return render(request,'task_con/successful.html', {'name': name, 'staues': staue, 'type': typee})
    # return HttpResponse("选择成功!")


def add(request):
    user_list = {i.user_account: [i.user_name, i.user_type] for i in users.objects.all()}
    if not request.session.get('account'):
        staue = 'login'
        name = '请登录'
        typee = '1209'
    else:
        staue = 'logout'
        name = user_list[request.session.get('account')][0]  # name
        typee = user_list[request.session.get('account')][1]  # user_type
    if request.method == "GET":
        return render(request, 'task_con/addfile.html', {'name': name, 'staues': staue, 'type': typee})
    a = request.POST.get("name")
    b = request.POST.get("rank_demand")
    c = request.POST.get("type")
    d = request.POST.get("label")
    e = request.POST.get("salary")
    f = request.POST.get("polish_time")
    g = request.POST.get("description")
    tishiyu = request.POST.get("tishi")
    label_list = list(d.split(','))
    setting = {}
    setting['labels'] = label_list
    setting['prompt'] = tishiyu
    setting = str(setting)
    user_list = {i.user_account: [i.user_id] for i in users.objects.all()}
    publisher_id = user_list[request.session.get('account')][0]
    Task.objects.create(task_name=a, task_rank=b, task_type=c, task_settings=setting,
                        task_salary=e, task_deadline_time=f, task_description=g, task_publish_id=publisher_id)
    global data_file_num
    print(data_file_num)
    data_list = DataUpload.objects.all()
    task_list = Task.objects.all()
    for row in task_list:
        if row.task_name == a:
            task_id = row.id
    for row in data_list:
        s = str(row.data_group)
        if s in data_file_num:
            Taskdata.objects.create(taskdata_id=row.id, taskdata_task_id=task_id,
                                    taskdata_content=row.data_content,taskdata_result="{'result':[]}")
    return redirect("task_market:user_mng:self")


def findfile(request):
    user_list = {i.user_account: [i.user_name, i.user_type] for i in users.objects.all()}
    if not request.session.get('account'):
        staue = 'login'
        name = '请登录'
        typee = '1209'
    else:
        staue = 'logout'
        name = user_list[request.session.get('account')][0]  # name
        typee = user_list[request.session.get('account')][1]  # user_type
    user_list = {i.user_account: [i.user_id] for i in users.objects.all()}
    publisher_id = user_list[request.session.get('account')][0]
    work_list = Task.objects.filter(task_publish_id=publisher_id)
    return render(request, 'task_con/findfile.html', {'work_list': work_list, 'name': name, 'staues': staue, 'type': typee})


def adddata(request):
    user_list = {i.user_account: [i.user_name, i.user_type] for i in users.objects.all()}
    if not request.session.get('account'):
        staue = 'login'
        name = '请登录'
        typee = '1209'
    else:
        staue = 'logout'
        name = user_list[request.session.get('account')][0]  # name
        typee = user_list[request.session.get('account')][1]  # user_type
    return render(request, 'task_con/adddata.html', {'name': name, 'staues': staue, 'type': typee})


def addtext(request):
    user_list = {i.user_account: [i.user_name, i.user_type] for i in users.objects.all()}
    if not request.session.get('account'):
        staue = 'login'
        name = '请登录'
        typee = '1209'
    else:
        staue = 'logout'
        name = user_list[request.session.get('account')][0]  # name
        typee = user_list[request.session.get('account')][1]  # user_type
    if request.method == "GET":
        return render(request, 'task_con/addtext.html', {'name': name, 'staues': staue, 'type': typee})
    myfile = request.FILES.get("thumnail")
    #publisher_id = request.session.get('user_id')#TODO
    user_list = {i.user_account: [i.user_id] for i in users.objects.all()}
    publisher_id = user_list[request.session.get('account')][0]
    work_list = DataUpload.objects.all()
    w = []
    for row in work_list:
        w.append(row.data_group)
    if len(w)==0:
        mk=0
    else:
        mk = max(w)
    with open(settings.TEXT_PATH+'\\'+'234.txt', 'wb') as d:
        for chunk in myfile.chunks():
            d.write(chunk)
    with open(settings.TEXT_PATH+'\\'+'234.txt', 'r') as d:
        key = 0
        s = []
        content_index = 0
        for row in d:
            key += 1
            a = list(row.split(','))
            dic = {}

            if key == 1:
                num = len(a)
                for i in range(num):
                    dic[a[i]] = '0'
                    s.append(a[i])
                for index,head in enumerate(s):
                    if 'content' in head:
                        content_index = index
                        break
                # content_index = s.index('content')
                print(content_index)
                print(s)
            else:
                #dic[s[content_index]] = a[content_index]
                # for i in range(num):
                #     dic[s[i]] = a[i]
                m = str(a[content_index])
                DataUpload.objects.create(data_group=mk + 1, data_content=m, data_upload_time=time.time(),publisher_id=publisher_id)
    return redirect("task_market:user_mng:self")#("http://127.0.0.1:8000/task_con/")

def generate_folder_name():
    timestamp = str(int(time.time()))  # Get current timestamp
    random_suffix = ''.join(random.choices(string.ascii_lowercase, k=5))  # Generate a random suffix
    folder_name = f"folder_{timestamp}_{random_suffix}"  # Combine timestamp and random suffix
    return folder_name

def addimage(request):
    user_list = {i.user_account: [i.user_name, i.user_type] for i in users.objects.all()}
    if not request.session.get('account'):
        staue = 'login'
        name = '请登录'
        typee = '1209'
    else:
        staue = 'logout'
        name = user_list[request.session.get('account')][0]  # name
        typee = user_list[request.session.get('account')][1]  # user_type
    if request.method == "GET":
        return render(request, 'task_con/addimage.html', {'name': name, 'staues': staue, 'type': typee})

    user_list = {i.user_account: [i.user_id] for i in users.objects.all()}
    publisher_id = user_list[request.session.get('account')][0]

    myimage = request.FILES.get("myimage")
    z = zipfile.ZipFile(myimage)

    # Create a folder with a unique name in the designated directory
    target_directory = settings.IMAGE_PATH  # Specify the target directory
    folder_name = generate_folder_name()
    new_folder_path = os.path.join(target_directory, folder_name)
    os.makedirs(new_folder_path, exist_ok=True)

    z.extractall(path=new_folder_path)
    #path_i = 'D:\DDocuments\\resource\image' + '\\' + str(m)
    p = []
    print(new_folder_path)
    for root, dirs, files in os.walk(new_folder_path):
        print(files)
        for i in range(len(files)):
            p.append(files[i])
    work_list = DataUpload.objects.all()
    w = []
    for row in work_list:
        w.append(row.data_group)
    if len(w) == 0:
        mk = 0
    else:
        mk = max(w)
    print('打印文件名：',p)
    for i in range(len(p)):
        image_path = folder_name + '/' + str(p[i])
        DataUpload.objects.create(data_type=1, data_group=mk + 1, data_content=image_path,
                                  data_upload_time=time.time(),publisher_id=publisher_id)
    return redirect("task_market:user_mng:self")


# def addimage2(request):
#     if request.method == "GET":
#         return render(request, 'task_con/addimage.html')
#
#     myimage = request.FILES.get("myimage")
#     z = zipfile.ZipFile(myimage)
#     z.extractall(path='D:\DDocuments\\resource\image')#(path=settings.IMAGE_PATH)
#     m = myimage.name[:-4]
#     path_i = 'D:\DDocuments\\resource\image' + '\\' + str(m)
#     p=[]
#     print(path_i)
#     for root, dirs, files in os.walk(path_i):
#         print(files)
#         for i in range(len(files)):
#             p.append(files[i])
#     work_list = DataUpload.objects.all()
#     w = []
#     for row in work_list:
#         w.append(row.data_group)
#     if len(w)==0:
#         mk=0
#     else:
#         mk = max(w)
#
#     for i in range(len(p)):
#         image_path = path_i + '/' + str(p[i])
#         DataUpload.objects.create(data_type=1, data_group=mk + 1, data_content=image_path,
#                                   data_upload_time=time.time())
#     return redirect("task_market:user_mng:self")
